<template>
  <div class="login">
    <el-form
      class="animate__animated"
      :model="form"
      ref="ruleFormRef"
      :rules="rules"
      scroll-to-error
      @keyup.enter="submit()"
      label-width="120px"
      size="large"
      :class="{ animate__fadeInLeft: isRegister, animate__fadeInRight: !isRegister }"
      label-position="top"
    >
      <div class="head">
        <h2>{{ isRegister ? "注册" : "登录" }}</h2>
        <el-button type="primary" size="small" @click="change"
          ><h4>{{ isRegister ? "去登录" : "去注册" }}</h4></el-button
        >
      </div>

      <el-form-item label="手机号" prop="phone">
        <el-input autofocus v-model="form.phone" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <div class="loginbtn">
          <el-input v-model="form.code" />
          <yzm :identifyCode="code" @click="getcode" />
        </div>
      </el-form-item>
      <el-form-item class="loginarea">
        <el-button :loading="isloading" type="primary" block @click="submit()">{{
          isRegister ? "完成注册" : "登录"
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { getCode, postLogin, postRegister, isOutData } from "@/api/login"
import { getMenusRote } from "@/api/menus"
import storage from "@/utils/storage"
import type { FormInstance, FormRules } from "element-plus"
import yzm from "@/components/yzm/yzmView.vue"

let form = reactive<any>({
  phone: "17516211205",
  password: "111",
  code: "",
})
const router = useRouter()
const route = useRoute()
const code = ref("")
const isloading = ref(false)
const isRegister = ref(false)
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  phone: [
    { required: true, message: "请输入手机号", trigger: ["blur"] },
    {
      pattern: /^1\d{10}$/,
      message: "手机号格式不正确",
      trigger: ["blur"],
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["blur"],
    },
  ],
  code: [
    {
      required: true,
      message: "请输入验证码",
      trigger: ["blur"],
    },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== code.value) {
          callback(new Error("验证码不正确"))
        } else {
          callback()
        }
      },
    },
  ],
})
const change = () => {
  isRegister.value = !isRegister.value
  getcode()
  ElNotification({
    title: "温馨提示",
    message: `${
      isRegister.value ? "页面进入注册状态，请填写注册信息" : "页面进入登录状态，请填写登录信息"
    }`,
    type: "success",
  })
  ruleFormRef.value?.resetFields()
}
const getcode = async () => {
  let res = await getCode("/bem/getCode")
  if (res.code == 200) {
    code.value = res.data.code
    form.code = res.data.code
  }
}
const init = async () => {
  try {
    let res = await isOutData("/bem/isoutdata")
    if (res.code == 200) {
      ElNotification({
        title: "温馨提示",
        message: "用户已登录，直接进入首页",
        type: "success",
      })
      router.push("/layout")
    } else {
      getcode()
    }
  } catch (error: any) {
    if (error?.code == 300) {
      ElMessage.error(error?.msg)
    }
  }
}
init()
// formEl: FormInstance | undefined
const submit = async () => {
  if (!ruleFormRef.value) return
  try {
    await ruleFormRef.value.validate(async (valid, fields: any) => {
      if (valid) {
        isloading.value = true
        if (!isRegister.value) {
          postRegister("/bem/login", form)
            .then((res) => {
              if (res.code == 200) {
                ElMessage.success(res.msg)
                storage.set("token", res.data.token)
                storage.set("userinfo", res.data.userinfo)
                storage.set("refresh_token", res.data.refresh_token)
                getMenusRote("/bem/menus/getMenuesRoutes").then((res) => {
                  if (res.code == 200) {
                    storage.set("allRoute", res.data)
                  }
                })
                router.push((route.query.redirect as string) || "/layout")
              } else {
                ElMessage.error(res.msg)
                getcode()
              }
            })
            .catch((err) => {
              ElMessage.error(JSON.stringify(err))
            })
            .finally(() => {
              isloading.value = false
            })
        } else {
          postLogin("/bem/register", form)
            .then((res) => {
              if (res.code == 200) {
                ElMessage.success(res.msg)
                change()
              } else {
                ElMessage.error(res.msg)
                getcode()
              }
            })
            .catch((err) => {
              ElMessage.error(JSON.stringify(err))
            })
            .finally(() => {
              isloading.value = false
            })
        }
      } else {
        ElMessage.error(fields[Object.keys(fields)[0]][0].message)
      }
    })
  } catch (error) {
    console.log("====================================")
    console.log("服务器网络异常")
    console.log("====================================")
  }
}
</script>
<style lang="scss" scoped>
.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.el-form-item:nth-child(4) {
  .el-input {
    width: 130px;
  }
}
.login {
  height: 100vh;
  overflow: hidden;
  display: flex;
  align-items: center;
  background-color: #eee;
  justify-content: center;
  .el-form {
    width: 340px;
    padding: 20px;
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 10px;
    .el-form-item {
      margin: 20px 0;
    }
  }
  h2 {
    margin: 10px 0;
  }
  .loginbtn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .loginarea {
    .el-button--primary {
      width: 100%;
      margin-top: 10px;
    }
  }
}
</style>
